//
//  CreateAccountMoreController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/17/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "CreateAccountMoreController.h"
#import "UniversityViewController.h"
#import "RelationshipViewControlle.h"
#import "CourseViewController.h"
#import "ModuleViewController.h"
#import "SchoolViewController.h"
#import "Extensions.h"
#import "HomeViewController.h"
#import "YPickerView.h"

#define kCATag 100

@implementation CreateAccountMoreController
@synthesize parentVC;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Private Method

- (void)applyAppearance
{
    [self.navigationItem setHidesBackButton:YES];
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"save-button" 
                                 target:self 
                                 action:@selector(save:)];
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    if (parentVC) {
        [self setTitle:@"Edit Account"];
    }else {
        [self setTitle:@"Create Account"];
    }
    
    [self.tableView setBackgroundView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg.png"]] autorelease]];
}

- (UITableViewCell*)createAccountCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"CreateAccountCell" owner:self options:nil]; 
    
    return [views objectAtIndex:0];
}

- (void)showDobUI:(BOOL)bShow
{
    if (bShow) {
        UIDatePicker *datePicker = (id)[[dobUI viewWithTag:1] viewWithTag:11];
        CGRect dobRect = CGRectMake(0, 460, 320, 460);
        
        if ([[[JGoUtility sharedCreateAccount] objectForKey:@"dob"] isKindOfClass:[NSDate class]]) {
            datePicker.date = [[JGoUtility sharedCreateAccount] objectForKey:@"dob"];
        }
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [self.navigationController.view addSubview:dobUI];
        dobUI.frame = dobRect;
        dobRect = CGRectMake(0, 20, 320, 416);
        dobUI.frame = dobRect;
        [UIView commitAnimations];
        self.view.userInteractionEnabled = NO;
    }
    else {
        self.view.userInteractionEnabled = YES;
        [UIView animateWithDuration:0.3 
                         animations:^{
                             CGRect dobRect = CGRectMake(0, 460, 320, 460);
                             dobUI.frame = dobRect;                               
                         }
                         completion:^(BOOL finished){    
                             [dobUI removeFromSuperview];
                         }];                
    }
}

- (BOOL)validToSave
{
    if ([[cell1 fieldTextWithTag:kCATag].text length] == 0) {
        [JGoUtility showAlert:@"Please enter your name."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cell1 fieldTextWithTag:kCATag].text forKey:@"name"];
    }
    
    if ([[cell2 fieldTextWithTag:kCATag].text length] == 0 ) {
        [JGoUtility showAlert:@"Please enter your surname."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cell2 fieldTextWithTag:kCATag].text forKey:@"surname"];
    }    

    
    return YES;
}

- (void)showYearView:(BOOL)bShow
{
    if (bShow) {
        CGRect yvRect = CGRectMake(0, 460, 320, 460);
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [self.navigationController.view addSubview:yearUI];
        yearUI.frame = yvRect;
        yvRect = CGRectMake(0, 20, 320, 416);
        yearUI.frame = yvRect;
        [UIView commitAnimations];
        
        self.view.userInteractionEnabled = NO;
    }
    else {        
        self.view.userInteractionEnabled = YES;
        
        [UIView animateWithDuration:0.3 
                         animations:^{
                             CGRect dobRect = CGRectMake(0, 460, 320, 460);
                             yearUI.frame = dobRect;                               
                         }
                         completion:^(BOOL finished){    
                             [yearUI removeFromSuperview];
                         }];                
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [cell1 release];
    [cell2 release];
    [cell3 release];
    [cell4 release];
    [cell5 release];
    [cell6 release];
    [cell7 release];
    [cell8 release];
    [cell9 release];
    [cell10 release];
    
    [self setTableView:nil];        
    [dobUI release];
    
    [parentVC release];
    [super dealloc];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

#pragma mark - Action

- (void)back:(id)sender
{
    if (parentVC) {
        [parentVC dismissModalViewControllerAnimated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }

}

- (void)save:(id)sender
{
    if ([self validToSave]) {
        [JGoUtility showProgressInView:self.view 
                                target:self
                                 title:@"Saving Your Profile..."
                              selector:@selector(delaySave:)];
    }
}

- (IBAction)checkGenderMan:(UIButton*)sender
{
    sender.selected = !sender.selected;
    [[JGoUtility sharedCreateAccount] setValue:(sender.selected ? @"1" : @"0") forKey:@"gender"];
    [self.tableView reloadData];
}

- (IBAction)checkGenderGirl:(UIButton*)sender
{
    sender.selected = !sender.selected;
    [[JGoUtility sharedCreateAccount] setValue:(sender.selected ? @"0" : @"1") forKey:@"gender"];    
    [self.tableView reloadData];    
}

- (IBAction)doneDOB:(id)sender
{
    UIDatePicker *datePicker = (id)[[dobUI viewWithTag:1] viewWithTag:11];
    [[JGoUtility sharedCreateAccount] setValue:datePicker.date forKey:@"dob"];
    [self showDobUI:NO];
    [self.tableView reloadData];
}

- (void)selectYear:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self showYearView:YES];
}

- (IBAction)doneYearView:(id)sender
{   
    YPickerView *yearPicker = (id)[[yearUI viewWithTag:1] viewWithTag:11];
    NSString *yearString = yearPicker.year;
    [[JGoUtility sharedCreateAccount] setValue:yearString forKey:@"u_year"];
    [self showYearView:NO];
    [self.tableView reloadData];
    
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch (indexPath.row) {
        case 0: {
            cell = cell1;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell fieldTextWithTag:kCATag].text = [[JGoUtility sharedCreateAccount] objectForKey:@"name"];            
            break;
        }
        case 1: {
            cell = cell2;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell fieldTextWithTag:kCATag].text = [[JGoUtility sharedCreateAccount] objectForKey:@"surname"];
            break;
        }
        case 2: {
            cell = cell3;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            NSDate *dob = [[JGoUtility sharedCreateAccount] objectForKey:@"dob"];
            
            if (dob) {
                NSString *dobString = [JGoUtility stringFromDate1:dob];
                [cell titleTextWithTag:kCATag].text = dobString;
            }
            
            break;
        }
        case 3: {
            cell = cell4;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            NSString *gender = [[JGoUtility sharedCreateAccount] objectForKey:@"gender"];
            UIButton *manCheck =  (id)[cell viewWithTag:1];
            UIButton *girlCheck = (id)[cell viewWithTag:2];            
            
            if ([gender isEqualToString:@"1"]) {
                manCheck.selected = YES;
                girlCheck.selected = NO;
            }
            else {
                manCheck.selected = NO;
                girlCheck.selected = YES;                
            }
            
            break;
        }
        case 4: {
            cell = cell5;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            NSString *userStatus = [[JGoUtility sharedCreateAccount] objectForKey:@"status"];
            [cell titleTextWithTag:kCATag].text = [JGoUtility stringForRelationshipStatus:[userStatus integerValue]];
            break;
        }
        case 5: {
            cell = cell6; 
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            [cell titleTextWithTag:kCATag].text = [[JGoUtility sharedCreateAccount] objectForKey:@"university"];
            break;
        }
        case 6: {
            cell = cell7;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            [cell titleTextWithTag:kCATag].text = [[JGoUtility sharedCreateAccount] objectForKey:@"u_year"];
            break;
        }
        case 7: {
            cell = cell8;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            [cell titleTextWithTag:101].text = [[JGoUtility sharedCreateAccount] objectForKey:@"course"];
            break;
        }
        case 8: {
            cell = cell9;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            [cell titleTextWithTag:kCATag].text = [JGoUtility stringFromArray:[[JGoUtility sharedCreateAccount] objectForKey:@"modules"]];
            break;
        }
        case 9: {
            cell = cell10;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            [cell titleTextWithTag:110].text = [[JGoUtility sharedCreateAccount] objectForKey:@"college"];
            break;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    switch (indexPath.row) {
        case 2: {
            [self showDobUI:YES];
            break;
        }            
        case 4: {
            RelationshipViewControlle *rlVC = [[[RelationshipViewControlle alloc] init] autorelease];
            [rlVC setRelationshipMode:RelationshipModeNew];
            [self.navigationController pushViewController:rlVC animated:YES];
            break;
        }
            
        case 5: {
            UniversityViewController *usVC = [[[UniversityViewController alloc] init] autorelease];
            [self.navigationController pushViewController:usVC animated:YES];
            break;
        }
       
        case 6: {
            [self showYearView:YES];
            break;
        }
            
        case 7: {
            CourseViewController *crseVC = [[[CourseViewController alloc] init] autorelease];
            [crseVC setCourseMode:CourseModeNew];
            [self.navigationController pushViewController:crseVC animated:YES];
            break;
        }

        case 8: {
            ModuleViewController *mVC = [[[ModuleViewController alloc] init] autorelease];
            [mVC setModuleMode:ModuleModeNew];
            [mVC setModules:[[JGoUtility sharedCreateAccount] objectForKey:@"modules"]];
            [self.navigationController pushViewController:mVC animated:YES];
            break;
        }
        case 9: {
            SchoolViewController *schVC = [[[SchoolViewController alloc] init] autorelease];
            [schVC setSchoolMode:SchoolModeNew];
            [self.navigationController pushViewController:schVC animated:YES];
            break;
        }

        default:
            break;
    }    
}

#pragma mark - TableView Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    
    switch (indexPath.row) {
        case 0: {  
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"name"];
            break;
        }
        case 1: {
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"surname"];            
            break;
        }
        case 6:{  
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"u_year"];            
            break;            
        }
        default:
            break;
    }
        
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];    
    
    switch (indexPath.row) {
        case 0: {  
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"name"];
            break;
        }
        case 1: {
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"surname"];            
            break;
        }
        case 6:{  
            [[JGoUtility sharedCreateAccount] setValue:textField.text forKey:@"u_year"];            
            break;            
        }
        default:
            break;
    }
}

#pragma mark - Delay Method

- (void)delaySave:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSString *modules = [JGoUtility stringFromArray:[[JGoUtility sharedCreateAccount] objectForKey:@"modules"]];
    NSString *dob = [JGoUtility stringFromDate1:[[JGoUtility sharedCreateAccount] objectForKey:@"dob"]];
    dob = dob ? dob : @"0000-00-00";
    modules = modules ? modules : @"";

    LOG(@"%@",[[JGoUtility sharedCreateAccount] description]);
    
    [JGoAPI updateProfileWithUserId:[[JGoUtility sharedCreateAccount] objectForKey:@"user_id"]
                               name:[[JGoUtility sharedCreateAccount] objectForKey:@"name"]
                            surname:[[JGoUtility sharedCreateAccount] objectForKey:@"surname"] 
                           birthDay:dob 
                             gender:[[JGoUtility sharedCreateAccount] objectForKey:@"gender"] 
                              email:[[JGoUtility sharedCreateAccount] objectForKey:@"email"]  
                             status:[[JGoUtility sharedCreateAccount] objectForKey:@"status"]
                            college:[[JGoUtility sharedCreateAccount] objectForKey:@"college"] 
                         university:[[JGoUtility sharedCreateAccount] objectForKey:@"university"] 
                             course:[[JGoUtility sharedCreateAccount] objectForKey:@"course"] 
                             u_year:[[JGoUtility sharedCreateAccount] objectForKey:@"u_year"] 
                             c_year:[[JGoUtility sharedCreateAccount] objectForKey:@"c_year"] 
                             degree:[[JGoUtility sharedCreateAccount] objectForKey:@"degree"] 
                            modules:modules 
                              thumb:[[JGoUtility sharedCreateAccount] objectForKey:@"thumb"]     
                              error:&error];
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        if (parentVC) {
            [parentVC dismissModalViewControllerAnimated:YES];
        }else {
            HomeViewController *hVC = [[[HomeViewController alloc] initWithNibName:@"HomeViewController"
                                                                            bundle:nil] autorelease];
            [self.navigationController pushViewController:hVC animated:YES];
        }

        }
            
    [progress hide:YES];
}

@end
